<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web文件传输系统</title>
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --info-color: #4895ef;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --text-color: #2b2d42;
            --border-radius: 8px;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }
    
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f2f5;
            color: var(--text-color);
            line-height: 1.6;
        }
    
        .container {
            max-width: 900px;
            margin: 40px auto;
            background-color: white;
            padding: 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            transition: var(--transition);
        }
    
        h1 {
            color: var(--primary-color);
            text-align: center;
            margin-bottom: 30px;
            font-weight: 600;
            font-size: 2.2rem;
            position: relative;
            padding-bottom: 15px;
        }
    
        h1::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 3px;
            background: linear-gradient(to right, var(--primary-color), var(--success-color));
            border-radius: 3px;
        }
    
        .upload-section, .download-section {
            margin-bottom: 30px;
            padding: 25px;
            border: 1px solid #e0e0e0;
            border-radius: var(--border-radius);
            background-color: white;
            transition: var(--transition);
        }
    
        .upload-section:hover, .download-section:hover {
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }
    
        h2 {
            margin-top: 0;
            color: var(--secondary-color);
            font-size: 1.4rem;
            font-weight: 500;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
    
        h2::before {
            content: '';
            display: inline-block;
            width: 5px;
            height: 20px;
            background-color: var(--primary-color);
            margin-right: 10px;
            border-radius: 3px;
        }
    
        input[type="file"] {
            width: 100%;
            padding: 12px;
            margin-bottom: 15px;
            border: 2px dashed #ddd;
            border-radius: var(--border-radius);
            background-color: var(--light-color);
            transition: var(--transition);
            cursor: pointer;
        }
    
        input[type="file"]:hover {
            border-color: var(--primary-color);
            background-color: rgba(67, 97, 238, 0.05);
        }
    
        input[type="text"] {
            width: 100%;
            padding: 12px 15px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 1rem;
            transition: var(--transition);
        }
    
        input[type="text"]:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            outline: none;
        }
    
        button {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            margin-right: 10px;
            transition: var(--transition);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    
        button:hover {
            opacity: 0.9;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }
    
        button:active {
            transform: translateY(0);
        }
    
        .progress-container {
            width: 100%;
            height: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
            margin: 15px 0;
            overflow: hidden;
        }
    
        .progress-bar {
            height: 100%;
            background: linear-gradient(to right, var(--primary-color), var(--success-color));
            border-radius: 5px;
            width: 0%;
            transition: width 0.5s ease;
        }
    
        #uploadStatus {
            margin-top: 10px;
            color: #6c757d;
            font-size: 0.9rem;
        }
    
        .file-item, .folder-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            transition: var(--transition);
        }
    
        .file-item:hover, .folder-item:hover {
            background-color: rgba(0, 0, 0, 0.02);
            transform: translateX(5px);
        }
    
        .file-item:last-child, .folder-item:last-child {
            border-bottom: none;
        }
    
        .download-btn {
            background-color: var(--info-color);
        }
    
        .delete-btn {
            background-color: var(--danger-color);
        }
    
        .folder-btn {
            background-color: var(--warning-color);
        }
    
        .nav-buttons {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
    
        .breadcrumb {
            margin-bottom: 20px;
            font-size: 1rem;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 5px;
        }
    
        .breadcrumb a {
            color: var(--primary-color);
            text-decoration: none;
            padding: 5px 10px;
            border-radius: var(--border-radius);
            transition: var(--transition);
        }
    
        .breadcrumb a:hover {
            background-color: rgba(67, 97, 238, 0.1);
            text-decoration: none;
        }
    
        .breadcrumb span {
            color: var(--text-color);
            opacity: 0.7;
        }
    
        .create-folder {
            display: flex;
            margin-bottom: 20px;
            gap: 10px;
        }
    
        .create-folder input {
            flex: 1;
        }
    
        .current-path {
            margin-bottom: 20px;
            padding: 15px;
            background-color: var(--light-color);
            border-radius: var(--border-radius);
            font-size: 0.95rem;
            color: var(--text-color);
            border-left: 4px solid var(--primary-color);
        }
    
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 20px;
            }
            
            h1 {
                font-size: 1.8rem;
            }
            
            .file-item, .folder-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .file-item > div, .folder-item > div {
                width: 100%;
                display: flex;
                justify-content: space-between;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Web文件传输系统</h1>
        
        <div class="upload-section">
            <h2>文件上传</h2>
            <div class="current-path" id="currentUploadPath">当前上传路径: 根目录</div>
            <input type="file" id="fileInput" multiple>
            <button id="uploadBtn">上传文件</button>
            <div id="uploadProgress" class="progress-container">
                <div id="uploadBar" class="progress-bar"></div>
            </div>
            <div id="uploadStatus"></div>
        </div>
        
        <div class="download-section">
            <h2>文件管理</h2>
            <div class="nav-buttons">
                <button id="createFolderBtn">创建文件夹</button>
                <button id="goUpBtn" disabled>返回上一级</button>
            </div>
            <div class="create-folder" id="createFolderInput" style="display: none;">
                <input type="text" id="folderNameInput" placeholder="输入文件夹名称">
                <button id="confirmCreateBtn">创建</button>
                <button id="cancelCreateBtn">取消</button>
            </div>
            <div id="breadcrumb" class="breadcrumb"></div>
            <div id="fileList"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:5000/api/files';

        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadBar = document.getElementById('uploadBar');
        const uploadStatus = document.getElementById('uploadStatus');
        const fileList = document.getElementById('fileList');
        const createFolderBtn = document.getElementById('createFolderBtn');
        const goUpBtn = document.getElementById('goUpBtn');
        const createFolderInput = document.getElementById('createFolderInput');
        const folderNameInput = document.getElementById('folderNameInput');
        const confirmCreateBtn = document.getElementById('confirmCreateBtn');
        const cancelCreateBtn = document.getElementById('cancelCreateBtn');
        const breadcrumb = document.getElementById('breadcrumb');
        const currentUploadPath = document.getElementById('currentUploadPath');

        let currentPath = '';

        // 获取文件列表
        async function fetchFileList(path = '') {
            try {
                const url = path ? `${API_BASE_URL}?path=${encodeURIComponent(path)}` : API_BASE_URL;
                const response = await fetch(url);
                if (!response.ok) throw new Error('获取文件列表失败');
                return await response.json();
            } catch (error) {
                console.error('Error:', error);
                uploadStatus.textContent = '获取文件列表失败: ' + error.message;
                return { files: [], folders: [] };
            }
        }

        // 上传文件
       // 上传文件
async function uploadFiles(files) {
    console.log('当前上传路径:', currentPath || '根目录'); // 添加这行打印当前路径
    const formData = new FormData();
    
    // 1. 先附加路径参数
    if (currentPath) {
        formData.append('path', currentPath); // 确保这是相对路径如"123"
    }
    
    // 2. 再附加文件
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]); 
    }

    // 3. 不要手动设置Content-Type！
    const response = await fetch(`${API_BASE_URL}/upload`, {
        method: 'POST',
        body: formData // 让浏览器自动设置headers
    });

    try {
        const xhr = new XMLHttpRequest();
        
        return new Promise((resolve, reject) => {
            xhr.upload.addEventListener('progress', (event) => {
                if (event.lengthComputable) {
                    const percent = (event.loaded / event.total) * 100;
                    uploadBar.style.width = `${percent}%`;
                    uploadStatus.textContent = `上传中: ${files[0].name} - ${Math.round(percent)}%`;
                }
            });

            xhr.addEventListener('load', () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(JSON.parse(xhr.responseText));
                } else {
                    reject(new Error(xhr.statusText));
                }
            });

            xhr.addEventListener('error', () => {
                reject(new Error('上传请求失败'));
            });

            xhr.open('POST', `${API_BASE_URL}/upload`, true);
            xhr.send(formData);
        });
    } catch (error) {
        console.error('上传错误:', error);
        throw error;
    }
}
        // 下载文件
        function downloadFile(filename) {
            uploadStatus.textContent = `开始下载: ${filename}`;
            const url = currentPath 
                ? `${API_BASE_URL}/download/${encodeURIComponent(filename)}?path=${encodeURIComponent(currentPath)}`
                : `${API_BASE_URL}/download/${encodeURIComponent(filename)}`;
            window.location.href = url;
        }

        // 删除文件
        async function deleteFile(filename) {
            try {
                const url = currentPath 
                    ? `${API_BASE_URL}/${encodeURIComponent(filename)}?path=${encodeURIComponent(currentPath)}`
                    : `${API_BASE_URL}/${encodeURIComponent(filename)}`;
                
                const response = await fetch(url, {
                    method: 'DELETE'
                });
                
                if (!response.ok) throw new Error('删除文件失败');
                
                const result = await response.json();
                uploadStatus.textContent = result.message;
                return true;
            } catch (error) {
                console.error('删除错误:', error);
                uploadStatus.textContent = '删除文件失败: ' + error.message;
                return false;
            }
        }

        // 创建文件夹
        async function createFolder(folderName) {
            try {
                const response = await fetch(`${API_BASE_URL}/folder`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: folderName,
                        path: currentPath
                    })
                });
                
                if (!response.ok) throw new Error('创建文件夹失败');
                
                const result = await response.json();
                uploadStatus.textContent = result.message;
                return true;
            } catch (error) {
                console.error('创建文件夹错误:', error);
                uploadStatus.textContent = '创建文件夹失败: ' + error.message;
                return false;
            }
        }

        // 删除文件夹
        async function deleteFolder(folderName) {
            try {
                const url = currentPath 
                    ? `${API_BASE_URL}/folder/${encodeURIComponent(folderName)}?path=${encodeURIComponent(currentPath)}`
                    : `${API_BASE_URL}/folder/${encodeURIComponent(folderName)}`;
                
                const response = await fetch(url, {
                    method: 'DELETE'
                });
                
                if (!response.ok) throw new Error('删除文件夹失败');
                
                const result = await response.json();
                uploadStatus.textContent = result.message;
                return true;
            } catch (error) {
                console.error('删除文件夹错误:', error);
                uploadStatus.textContent = '删除文件夹失败: ' + error.message;
                return false;
            }
        }

        // 进入文件夹
        function enterFolder(folderName) {
            currentPath = currentPath ? `${currentPath}/${folderName}` : folderName;
            renderFileList();
            updateBreadcrumb();
            updateCurrentPath();
            goUpBtn.disabled = false;
        }

        // 返回上一级
        function goUp() {
            if (!currentPath) return;
            
            const pathParts = currentPath.split('/');
            pathParts.pop();
            currentPath = pathParts.join('/');
            
            renderFileList();
            updateBreadcrumb();
            updateCurrentPath();
            goUpBtn.disabled = currentPath === '';
        }

        // 更新面包屑导航
        function updateBreadcrumb() {
            if (!currentPath) {
                breadcrumb.innerHTML = '<span>根目录</span>';
                return;
            }
            
            const parts = currentPath.split('/');
            let html = '<a href="#" data-path="">根目录</a>';
            let current = '';
            
            for (let i = 0; i < parts.length; i++) {
                current += (current ? '/' : '') + parts[i];
                html += ` / <a href="#" data-path="${current}">${parts[i]}</a>`;
            }
            
            breadcrumb.innerHTML = html;
            
            // 添加面包屑导航点击事件
            breadcrumb.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    const path = e.target.getAttribute('data-path');
                    currentPath = path || '';
                    renderFileList();
                    updateBreadcrumb();
                    updateCurrentPath();
                    goUpBtn.disabled = currentPath === '';
                });
            });
        }

        // 更新当前路径显示
        function updateCurrentPath() {
            currentUploadPath.textContent = `当前上传路径: ${currentPath ? currentPath : '根目录'}`;
        }

        // 渲染文件列表
        async function renderFileList() {
            fileList.innerHTML = '<p>加载中...</p>';
            const data = await fetchFileList(currentPath);
            
            if (data.files.length === 0 && data.folders.length === 0) {
                fileList.innerHTML = '<p>当前目录为空</p>';
                return;
            }
            
            fileList.innerHTML = '';
            
            // 渲染文件夹
            data.folders.forEach(folder => {
                const folderItem = document.createElement('div');
                folderItem.className = 'folder-item';
                
                const folderInfo = document.createElement('span');
                folderInfo.textContent = `${folder.name}/`;
                
                const enterBtn = document.createElement('button');
                enterBtn.className = 'folder-btn';
                enterBtn.textContent = '进入';
                enterBtn.onclick = () => enterFolder(folder.name);
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'delete-btn';
                deleteBtn.textContent = '删除';
                deleteBtn.onclick = async () => {
                    const success = await deleteFolder(folder.name);
                    if (success) await renderFileList();
                };
                
                folderItem.appendChild(folderInfo);
                folderItem.appendChild(enterBtn);
                folderItem.appendChild(deleteBtn);
                
                fileList.appendChild(folderItem);
            });
            
            // 渲染文件
            data.files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                
                const fileInfo = document.createElement('span');
                fileInfo.textContent = `${file.name} (${file.size})`;
                
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = '下载';
                downloadBtn.onclick = () => downloadFile(file.name);
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'delete-btn';
                deleteBtn.textContent = '删除';
                deleteBtn.onclick = async () => {
                    const success = await deleteFile(file.name);
                    if (success) await renderFileList();
                };
                
                fileItem.appendChild(fileInfo);
                fileItem.appendChild(downloadBtn);
                fileItem.appendChild(deleteBtn);
                
                fileList.appendChild(fileItem);
            });
        }

        // 事件监听
        // 事件监听
        uploadBtn.addEventListener('click', async () => {
    const files = fileInput.files;
    if (files.length === 0) {
        uploadStatus.textContent = '请选择要上传的文件';
        return;
    }
    
    console.log('点击上传按钮时的路径:', currentPath || '根目录');
    
    try {
        uploadBar.style.width = '0%';
        const result = await uploadFiles(files);
        uploadStatus.textContent = '文件上传成功!';
        
        // 上传成功后重置文件输入
        fileInput.value = '';  // 这行代码会清除选择的文件
        
        await renderFileList();
    } catch (error) {
        uploadStatus.textContent = '上传失败: ' + error.message;
    }
});

        createFolderBtn.addEventListener('click', () => {
            createFolderInput.style.display = 'flex';
            folderNameInput.focus();
        });

        confirmCreateBtn.addEventListener('click', async () => {
            const folderName = folderNameInput.value.trim();
            if (!folderName) {
                uploadStatus.textContent = '请输入文件夹名称';
                return;
            }
            
            const success = await createFolder(folderName);
            if (success) {
                folderNameInput.value = '';
                createFolderInput.style.display = 'none';
                await renderFileList();
            }
        });

        cancelCreateBtn.addEventListener('click', () => {
            folderNameInput.value = '';
            createFolderInput.style.display = 'none';
        });

        goUpBtn.addEventListener('click', goUp);

        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            renderFileList();
            updateBreadcrumb();
            updateCurrentPath();
            goUpBtn.disabled = true;
        });
    </script>
</body>
</html>